package com.xczl.demo.test;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.xczl.demo.domain.Goods;
import com.xczl.demo.domain.filter.GoodsFilter;
import com.xczl.demo.service.GoodsService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:root-context.xml" })
public class GoodsServiceTestCase {

	@Autowired
	private GoodsService goodsService;

	/**
	 * 添加商品
	 */
	@Test
	@Transactional
	public void addTest() {
		Goods goods = createGoods();
		goodsService.add(goods);
		Goods temp = goodsService.findById(goods.getGoodsId());
		Assert.notNull(temp);
	}

	private Goods createGoods() {
		Goods goods = new Goods();
		goods.setCateId(1);
		goods.setName("佳能原装UV镜750D 700D 70D 760D 80D 67mm58mm72mm82mm77mm 滤镜");
		goods.setPicUrl("/a/a.jpg");
		goods.setPrice(BigDecimal.valueOf(200.00));
		goods.setState(Goods.STATE_NO);
		return goods;
	}

	/**
	 * 更新商品
	 */
	@Test
	@Transactional
	public void updateTest() {
		// 添加商品
		Goods goods = createGoods();
		goodsService.add(goods);
		// 下架
		goodsService.updateState(Goods.STATE_Off, goods.getGoodsId());
		// 修改商品
		goods.setCateId(2);
		goods.setName("佳能原装UV镜");
		goods.setPicUrl("/a/b.jpg");
		goods.setPrice(BigDecimal.valueOf(35.00));
		goods.setState(Goods.STATE_Off);
		goodsService.update(goods);
		// 比对修改
		Goods temp = goodsService.findById(goods.getGoodsId());
		Assert.notNull(temp);
		Assert.isTrue(StringUtils.equals(goods.getName(), temp.getName()));// 比名称
		Assert.isTrue(StringUtils.equals(goods.getPicUrl(), temp.getPicUrl()));// 比图片地址
		Assert.isTrue(goods.getCateId().equals(temp.getCateId()));// 比分类
		Assert.isTrue(goods.getPrice().compareTo(temp.getPrice()) == 0);// 比价格
		Assert.isTrue(goods.getState().equals(temp.getState()));// 比状态
	}

	/**
	 * 条件查询
	 */
	@Test
	@Transactional
	public void findByConditionTest() {
		// 设置条件
		GoodsFilter filter = new GoodsFilter();
		//filter.setStartPrice(BigDecimal.valueOf(100));
		filter.setEndPrice(BigDecimal.valueOf(300));
		//filter.setCateId(1);
		//filter.setName("春季新款");
		// 设置排序
		//filter.setOrderBy(GoodsFilter.ORDER_BY_PRICE);
		List<Goods> list = goodsService.findByCondition(filter);
		for (Goods temp : list) {
			System.out.println(temp.getName() + "\t" + temp.getPrice());
		}
	}
}
